package com.kongfuzi.student.app;

import android.app.Application;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;

import com.kongfuzi.student.R;
import com.kongfuzi.student.bean.User;
import com.kongfuzi.student.support.volley.RequestQueue;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.kongfuzi.student.support.utils.ArgsConstants;
import com.kongfuzi.student.support.utils.Util;
import com.kongfuzi.student.support.volley.toolbox.Volley;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.xutils.DbManager;
import org.xutils.db.DbManagerImpl;
import org.xutils.x;

import java.io.File;

/**
 * Created by cfan_yang on 2015/12/24.
 */
public class GasApplication extends Application {

    //正式打包前，将该值改方false
    public static final boolean DEBUG_MOD = true;
    private static final String TAG = "GasApplication";
    private static GasApplication mInstance;
    private static RequestQueue mRequestQueue;
    private static SharedPreferences mSharedPreferences = null;
    private static SharedPreferences.Editor mEditor = null;
    private static DbManager mCacheDbManager = null;
    // 微信APPID
    public static final String APP_ID = "wxc8c5f0de7e6f52a6";
    // 微信商户号
    public static final String MCH_ID = "1237752602";
    // 微信API密钥，在商户平台设置
    public static final String API_KEY = "546B81028427A64421F7B0691D0AB32D";
    private static IWXAPI msgApi;

    @Override
    public void onCreate() {
        super.onCreate();
        //多进程会导致Applicaton的onCreate多次调用，所有初始化操作放在该方法中执行
        mInstance = this;
        init();

    }

    private void init() {{
        if (Util.getProcessName(android.os.Process.myPid()).equals(getPackageName())) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
            {//SD卡存在,缓存等相关文件创建在SD卡
                File SD_CACHE_DIR = new File(ArgsConstants.SD_DIR + ArgsConstants.CACHE_DIR);
                if (!SD_CACHE_DIR.exists()) {
                    SD_CACHE_DIR.mkdirs();
                }
            } else {//SD卡不存在，缓存等相关文件创建在/data目录下
                File DATA_CACHE_DIR = new File(ArgsConstants.DATA_DIR + ArgsConstants
                        .PACKAGE_NAME + ArgsConstants.CACHE_DIR);
                if (!DATA_CACHE_DIR.exists()) {
                    DATA_CACHE_DIR.mkdirs();
                }
            }

            //初始化xUtils3
            x.Ext.init(this);
            x.Ext.setDebug(DEBUG_MOD);

            //创建Volley的RequestQueue
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());

            //初始化SharedPreferences
            mSharedPreferences = getSharedPreferences(ArgsConstants.USER_INFO, MODE_PRIVATE);
            mEditor = mSharedPreferences.edit();

            //初始化缓存数据库
            DbManager.DaoConfig daoConfig = new DbManager.DaoConfig();
            daoConfig.setDbName(ArgsConstants.DB_CACHE_NAME);
            daoConfig.setDbDir(new File(ArgsConstants.DB_CACHE_DIR));
            mCacheDbManager = DbManagerImpl.getInstance(daoConfig);

            //初始化ImageLoader
            File cacheDir = StorageUtils.getOwnCacheDirectory(this, ArgsConstants.CACHE_DIR +
                    "image/");
            DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().cacheInMemory
                    (true).cacheOnDisk(true).considerExifParams(true).imageScaleType
                    (ImageScaleType.EXACTLY).bitmapConfig(Bitmap.Config.RGB_565).displayer(new
                    FadeInBitmapDisplayer(100)).resetViewBeforeLoading(true).showImageOnLoading(R
                    .drawable.shape_default_pic).showImageForEmptyUri(R.drawable.shape_default_pic)
                    .showImageOnFail(R.drawable.shape_default_pic).build();
            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                    .denyCacheImageMultipleSizesInMemory().diskCache(new UnlimitedDiskCache(cacheDir))
                    .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
                    .defaultDisplayImageOptions(defaultOptions)
                    .tasksProcessingOrder(QueueProcessingType.LIFO).build();
            com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
            //初始化微信
            msgApi = WXAPIFactory.createWXAPI(this, null);
            msgApi.registerApp(GasApplication.APP_ID);
        }
    }

    }

    public static IWXAPI getWXAPI() {
        return msgApi;
    }

    public static GasApplication getInstance() {
        return mInstance;
    }

    /**
     * 保存 secretkey(token)
     */
    public static void putSecretkey(String key) {
        mEditor.putString(ArgsConstants.SECRETKEY,key).commit();
    }

    /**
     * 得到 secretkey(token)
     */
    public static String getSecretkey() {
        return mSharedPreferences.getString(ArgsConstants.SECRETKEY, "");
    }

    public static DbManager getCacheDbManager() {
        return mCacheDbManager;
    }

    /**
     * 获取Volley的RequestQueue
     */
    public static RequestQueue getRequestQueue() {
        return mRequestQueue;
    }

    /**
     * 保存用户ID
     */
    public static void putUserId(String id) {
        mEditor.putString(ArgsConstants.USER_ID, id).commit();
    }

    /**
     * 获取用户ID,如果没有登录返回空字符串
     */
    public static String getUserId() {
        return mSharedPreferences.getString(ArgsConstants.USER_ID,"");
    }

    /**
     * 通过user id来判断是否登录
     */
    public static boolean isLogin() {
        if(TextUtils.isEmpty(getUserId())) {
            return false;
        }
        return true;
    }

    /**
     * 存储登录的手机号码
     */
    public static void putMobileNumber(String number) {
        mEditor.putString(ArgsConstants.MOBILE_NUMBER, number).commit();
    }

    /**
     * 获取登录的手机号码
     */
    public static String getMobileNubmer() {
        return mSharedPreferences.getString(ArgsConstants.MOBILE_NUMBER, "");
    }

    /**
     * 存储用户编号
     */
    public static void putUserCnumber(String number) {
        mEditor.putString(ArgsConstants.USER_CNUMBER, number).commit();
    }

    /**
     * 获取用户编号
     */
    public static String getUserCnumber() {
        return mSharedPreferences.getString(ArgsConstants.USER_CNUMBER, "");
    }

    /**
     * 保存User
     */
    public static void saveUser(User user) {
        putUserId(user.id);
        putMobileNumber(user.mobile);
        putSecretkey(user.token);
        putUserCnumber(user.cnumber);
    }

    /**
     * 保存验证码
     */
    public static void putCaptcha(String code) {
        mEditor.putString(ArgsConstants.CAPTCHA, code).commit();
    }

    /**
     * 获取验证码
     */
    public static String getCaptcha() {
        return mSharedPreferences.getString(ArgsConstants.CAPTCHA, "");
    }
}
